package work.chenxr.knife4j.config;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.HeaderParameter;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import work.chenxr.knife4j.enums.ErrorCode;

import java.util.Arrays;

/**
 * @Author Chenxr
 * @Date 2023/09/11
 * @Description 接口文档配置
 */
@Configuration
public class Knife4jConfig {
    /**
     * 全局请求头
     */
    private static final String AUTH_HEADER = "Authorization";

    /**
     * 请求头前缀
     */
    private static final String AUTH_HEADER_PREFIX = "Bearer ";

    @Bean
    public OperationCustomizer operationCustomizer() {
        return (operation, handlerMethod) -> {
            // 添加全局请求头参数
            operation.addParametersItem(new HeaderParameter().schema(new StringSchema()._default(AUTH_HEADER_PREFIX)).name(AUTH_HEADER));

            // 添加全局状态响应码
            ApiResponses responses = operation.getResponses();
            Arrays.stream(ErrorCode.values()).forEach(errorCode -> {
                responses.addApiResponse(String.valueOf(errorCode.getCode()), new ApiResponse().description(errorCode.getMsg()));
            });

            return operation;
        };
    }

    @Bean
    public GroupedOpenApi groupOneApi(OperationCustomizer operationCustomizer) {
        String[] paths = {"/one/**"};
        String[] packagedToMatch = {"work.chenxr.knife4j.one"};
        return GroupedOpenApi.builder()
                .group("分组1")
                .pathsToMatch(paths)
                .packagesToScan(packagedToMatch)
                .addOperationCustomizer(operationCustomizer)
                .build();
    }

    @Bean
    public GroupedOpenApi adminApi(OperationCustomizer operationCustomizer) {
        String[] paths = {"/two/**"};
        String[] packagedToMatch = {"work.chenxr.knife4j.two"};
        return GroupedOpenApi.builder()
                .group("分组2")
                .pathsToMatch(paths)
                .packagesToScan(packagedToMatch)
                .addOperationCustomizer(operationCustomizer)
                .build();
    }


    @Bean
    public OpenAPI customOpenAPI() {
        Info info = new Info()
                .title("API DOC")
                .description("接口文档")
                .contact(new Contact().name("Author Name"));
        return new OpenAPI().info(info);
    }
}
